﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using CommonLib;
using System.Collections;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;

namespace FormLib
{
    public partial class DJCalForm : DevExpress.XtraEditors.XtraForm
    {
        private GridEditorCollection gridEditors;
        private CommonLib.AccessDB m_accessDB_xyzb;
        private IFeatureLayer m_FeatureLayer = null;
        private IFeature m_Feature = null;
        private bool isSaved = false;
        double m_zdjg = 0.0;
        double m_crjg = 0.0;
        //读取配置文件，获取修正因子
        private CommonLib.XMLConfig m_DB_YSZB_Config = new CommonLib.XMLConfig("DB_YSZB_Config.xml");
        private string m_calContent;
        private int bddj = -1;

        private string lcfp_tableName = "";
        public DJCalForm(IFeatureLayer featureLayer, IFeature feature, string calContent, string jzdj, string jzjb)
        {
            InitializeComponent();
            m_FeatureLayer = featureLayer;
            m_Feature = feature;
            this.bddj = Convert.ToInt16(jzdj);

            int statusFlag = CommonLib.CommonTools.MapMouseFlag;
            if (statusFlag == 30001 || statusFlag == 30002 || statusFlag == 30003 || statusFlag == 30004 || statusFlag == 30005 || statusFlag == 30006)
            {
                this.labelControl4.Text = "标定地价:";
            }
            //this.labelControl4.Text

            if (m_Feature.Fields.FindField("ZDJG") == -1)
            {
                MessageBox.Show("请先对数据进行处理！");
                return;
            }
            try
            {
                string path_xyzb = ConfigsAllocator.appStartPath + "DataBase\\XY_ZBTX_DB.mdb";
                m_accessDB_xyzb = new CommonLib.AccessDB(path_xyzb, "byPath");
                m_calContent = calContent;
                this.txtEJZDJ.Text = jzdj;
                this.txtEJZJB.Text = jzjb;
                this.gridEditors = new GridEditorCollection();
                InitInplaceEditors(m_calContent);
                this.gdcXZYZ.DataSource = gridEditors;
                this.DEStart.EditValue = DateTime.Now.ToString();
                this.DEEnd.EditValue = DateTime.Now.AddMonths(1).ToString();
            }
            catch (Exception ex)
            {
                COM.LIB.LOG.LogOperator.WriteLog(ex.Message);
            }
        }

        private void sBtnCal_Click(object sender, EventArgs e)//测算
        {
            try
            {
                this.lblCalResult.Text = "";
                m_zdjg = 0.0;
                if (this.txtEJZDJ.Text == null || this.txtEJZJB.Text == null)
                {
                    MessageBox.Show("请先确定相关参数！");
                    this.txtEJZDJ.Focus();
                    return;
                }
                else if (Convert.ToDateTime(this.DEEnd.Text) < Convert.ToDateTime(this.DEStart.Text))
                {
                    MessageBox.Show("请输入正确的期数起始时间。");
                    return;
                }
                string jzjb = this.txtEJZJB.Text.Trim();
                //修正系数
                string[] xzxsArray = new string[this.gdvXZYZ.RowCount];
                for (int i = 0; i < this.gdvXZYZ.RowCount; i++)
                {
                    string zbName = this.gdvXZYZ.GetRowCellValue(i, "Name").ToString().Trim();
                    string zbFieldValue = this.gdvXZYZ.GetRowCellValue(i, "Value").ToString().Trim();
                    if (zbName != "")
                    {
                        string zbtable = "";
                        string zbField="";
                        string whereClause = "where 1=1 ";
                        zbtable = m_DB_YSZB_Config.GetAttributeValueListFromNodeNameWithSpecialAttribute("calContent", "value", m_calContent, "XZZB", "table", "name", zbName)[0];
                        zbField = m_DB_YSZB_Config.GetAttributeValueListFromNodeNameWithSpecialAttribute("calContent", "value", m_calContent, "XZZB", "field", "name", zbName)[0];
                        if (zbName.Equals("临街深度") || zbName.Equals("宽深比"))
                        {
                            string[] fieldArray = zbField.Split('|');
                            string[] fieldValueArray = zbFieldValue.Split('-');
                            if (fieldArray[0].Contains("MIN"))
                            {
                                whereClause += " and " + fieldArray[0] + "=" + fieldValueArray[0] + " and " + fieldArray[1] + "=" + fieldValueArray[1];
                            }
                            else
                            {
                                whereClause += " and " + fieldArray[0] + "=" + fieldValueArray[1] + " and " + fieldArray[1] + "=" + fieldValueArray[0];
                            }
                        }
                        else if (zbName.StartsWith("楼层分配率"))
                        {
                            zbtable = lcfp_tableName;
                            string[] fieldArray = zbField.Split('|');
                            string[] fieldValueArray = zbFieldValue.Split('|');
                            if (fieldArray[0].Contains("ZCS"))
                            {
                                whereClause += " and " + fieldArray[0] + "=" + fieldValueArray[0] + " and " + fieldArray[1] + "=" + fieldValueArray[1];
                            }
                            else
                            {
                                whereClause += " and " + fieldArray[0] + "=" + fieldValueArray[1] + " and " + fieldArray[1] + "=" + fieldValueArray[0];
                            }
                        }
                        else if (zbName.Contains("开发程度") || zbName.Contains("区位因素"))
                        {
                            //string[] fieldArray = zbField.Split('|');
                            //string[] fieldValueArray = zbFieldValue.Split('|');
                            //if (fieldArray[0].Equals("JB"))
                            //{
                            //    whereClause += " and " + fieldArray[0] + "=" + fieldValueArray[0] + " and " + fieldArray[1] + "='" + fieldValueArray[1].Trim() + "'";
                            //}
                            //else
                            //{
                            //    whereClause += " and " + fieldArray[0] + "='" + fieldValueArray[1].Trim() + "' and " + fieldArray[1] + "=" + fieldValueArray[0];
                            //}



                            switch (jzjb)
                            {
                                case "Ⅰ":
                                    whereClause += " and  JB = 1 and " + zbField + "='" + zbFieldValue + "'";
                                    break;
                                case "Ⅱ":
                                    whereClause += " and  JB = 2 and " + zbField + "='" + zbFieldValue + "'";
                                    break;
                                case "Ⅲ":
                                    whereClause += " and  JB = 3 and " + zbField + "='" + zbFieldValue + "'";
                                    break;
                                case "Ⅳ":
                                    whereClause += " and  JB = 4 and " + zbField + "='" + zbFieldValue + "'";
                                    break;
                                case "Ⅴ":
                                    whereClause += " and  JB = 5 and " + zbField + "='" + zbFieldValue + "'";
                                    break;
                                default:
                                    whereClause += " and " + zbField + "=" + zbFieldValue + "'";
                                    break;
                            }

                        }
                        else if (zbName.Contains("容积率") || zbName.Contains("形状") || zbName.Contains("街角地") || zbName.Contains("景观环境") || zbName.Contains("二级分类") || zbName.Contains("楼层类型") || zbName.Contains("临路条件"))
                        {
                            whereClause += " and " + zbField + "= '" + zbFieldValue.Trim() + "'";
                        }
                        else
                        {
                            whereClause += " and " + zbField + "=" + zbFieldValue;
                        }
                        string SQLStr = "select XZXS from " + zbtable + " " + whereClause;
                        DataRow dr = m_accessDB_xyzb.getDataRow(SQLStr);
                            xzxsArray[i] = dr[0].ToString();
                    }
                }
                //确定计算参数
                double jzdj = double.Parse(this.txtEJZDJ.Text.Trim());
                ////期日修正系数（1+0.0037*月数）
                //int mouths = CommonTools.GetMonth(this.DEStart.Text, this.DEEnd.Text);
                //double qrxz;
                //if (m_calContent.Contains("商业") || m_calContent.Contains("住宅"))
                //{
                //    qrxz = 1 + 0.0037 * mouths;
                //}
                //else
                //{
                //    qrxz = 1 + 0.0015 * mouths;
                //}
                //double zdjg = jzdj * qrxz;
                double zdjg = jzdj;//不考虑期日修正
                for (int i = 0; i < xzxsArray.Length; i++)
                {
                    zdjg = zdjg * double.Parse(xzxsArray[i].ToString().Trim());
                }
                m_zdjg = Math.Round(double.Parse(zdjg.ToString()), 0);
                m_crjg = Math.Round(double.Parse(zdjg.ToString()), 0);
                int statusFlag = CommonLib.CommonTools.MapMouseFlag;
                if (statusFlag == 30004 || statusFlag == 30005 || statusFlag == 30006)
                {
                    this.lblCalResult.Text = "出让价格为：" + m_crjg + " 元";
                }
                else
                {
                    this.lblCalResult.Text = "宗地价格为：" + m_zdjg + " 元";
                }
            }
            catch (Exception ex)
            {
                COM.LIB.LOG.LogOperator.WriteLog(ex.Message);
            }
        }

        private void sBtnSave_Click(object sender, EventArgs e)//保存
        {
            int statusFlag = CommonLib.CommonTools.MapMouseFlag;
            try
            {
                //保存测算结果
                if (this.lblCalResult.Text == "")
                {
                    MessageBox.Show("请先进行测算");
                    return;
                }
                if (isSaved)
                {
                    MessageBox.Show("保存成功!");
                }
                else
                {
                    IDataset pDataset = (IDataset)m_FeatureLayer.FeatureClass;
                    if (null == pDataset)
                    {
                        MessageBox.Show("基准图层为空！");
                        return;
                    }

                    #region 初始化要更新字段的字段名、字段Index(Array)
                    //string fieldName = "ZDJG";
                    #endregion

                    IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit)pDataset.Workspace;
                    try
                    {

                        #region 开始编辑
                        if (!pWorkspaceEdit.IsBeingEdited())
                        {
                            pWorkspaceEdit.StartEditing(true);
                        }
                        pWorkspaceEdit.StartEditOperation();
                        #endregion
                        #region 编辑
                        if (statusFlag == 30001 || statusFlag == 30002 || statusFlag == 30003)
                        {
                            m_Feature.set_Value(m_Feature.Fields.FindField("BDDJ_TMP"), this.bddj);
                            m_Feature.set_Value(m_Feature.Fields.FindField("ZDJG2"), m_zdjg);//设定按标定地价计算宗地价格
                        }
                        if (statusFlag == 30004 || statusFlag == 30005 || statusFlag == 30006)
                        {
                            m_Feature.set_Value(m_Feature.Fields.FindField("CRJG"), m_crjg);
                        }
                        else
                        {
                            m_Feature.set_Value(m_Feature.Fields.FindField("ZDJG"), m_zdjg);
                        }
                        m_Feature.Store();
                        #endregion

                        #region 结束编辑
                        pWorkspaceEdit.StopEditOperation();
                        if (pWorkspaceEdit.IsBeingEdited())
                        {
                            pWorkspaceEdit.StopEditing(true);
                            MessageBox.Show("保存成功!");
                            isSaved = true;
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkspaceEdit);
                    }
                }
            }
            catch (Exception ex)
            {
                COM.LIB.LOG.LogOperator.WriteLog(ex.Message);
            }

        }

        void InitInplaceEditors(string calContent)
        {
            try
            {
                List<string> zbNameList = m_DB_YSZB_Config.GetAttributeValueListFromNodeName("calContent", "value", calContent, "XZZB", "name");
                List<string> zbTableList = m_DB_YSZB_Config.GetAttributeValueListFromNodeName("calContent", "value", calContent, "XZZB", "table");
                List<string> zbFieldList = m_DB_YSZB_Config.GetAttributeValueListFromNodeName("calContent", "value", calContent, "XZZB", "field");
                #region 读取指标名称
                if (zbNameList.Count > 0)
                {
                    for (int i = 0; i < zbNameList.Count; i++)
                    {
                        string zbName = zbNameList[i];
                        string zbTable = zbTableList[i];
                        string zbField = zbFieldList[i];
                        string[] fieldArray = zbField.Split('|');
                        string field = fieldArray[0];
                        string whereClause = " where 1=1";
                        for (int o = 1; o < fieldArray.Length; o++)
                        {
                            field += " ," + fieldArray[o];
                        }
                        string SQLStr = "select " + field + " from " + zbTable;
                        if (zbName.Contains("区位因素") || zbName.Contains("开发程度"))
                        {
                            string jzjb = this.txtEJZJB.Text;
                            switch (jzjb)
                            {
                                case "Ⅰ":
                                    whereClause += " and  JB = 1";
                                    break;
                                case "Ⅱ":
                                    whereClause += " and  JB = 2";
                                    break;
                                case "Ⅲ":
                                    whereClause += " and  JB = 3";
                                    break;
                                case "Ⅳ":
                                    whereClause += " and  JB = 4";
                                    break;
                                case "Ⅴ":
                                    whereClause += " and  JB = 5";
                                    break;
                                default:
                                    whereClause += "";
                                    break;
                            }
                        }
                        else if (zbName.StartsWith("楼层分配率"))
                        {
                            continue;
                        }
                        SQLStr += whereClause;
                        DataTable dt = m_accessDB_xyzb.getDataTable(SQLStr);
                        RepositoryItemComboBox repositoryItemComboBox = new RepositoryItemComboBox();
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            if (zbName.Equals("临街深度") || zbName.Equals("宽深比"))
                            {
                                string cmbValue = dt.Rows[j][0].ToString() + " - " + dt.Rows[j][1].ToString();
                                repositoryItemComboBox.Items.Add(cmbValue);
                            }
                            else if (zbName.StartsWith("楼层类型"))
                            {
                                string cmbValue = dt.Rows[j][0].ToString();
                                repositoryItemComboBox.Items.Add(cmbValue);
                                //continue;
                           
                            }
                            //else if (zbName.StartsWith("楼层分配率"))
                            //{
                            //    break;
                            //    //string cmbValue = dt.Rows[j][0].ToString() + " | " + dt.Rows[j][1].ToString();
                            //    //repositoryItemComboBox.Items.Add(cmbValue);

                            //}
                            else
                            {
                                string cmbValue = dt.Rows[j][0].ToString();
                                repositoryItemComboBox.Items.Add(cmbValue);
                            }
                        }
                        if (zbName.StartsWith("楼层类型"))
                        {
                            repositoryItemComboBox.SelectedIndexChanged += new EventHandler(lcfp_SelectedIndexChanged);
                            this.gridEditors.Add(repositoryItemComboBox, zbName, repositoryItemComboBox.Items[0].ToString());
                            lcfp_SelectedIndexChanged(null,null);
                        }
                        else
                        {
                            this.gridEditors.Add(repositoryItemComboBox, zbName, repositoryItemComboBox.Items[0].ToString());
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                COM.LIB.LOG.LogOperator.WriteLog(ex.Message);
            }

        }

        private void gdvXZYZ_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            if (e.Column == this.gridColXZYZValue)
            {
                GridEditorItem item = this.gdvXZYZ.GetRow(e.RowHandle) as GridEditorItem;
                if (item != null) e.RepositoryItem = item.RepositoryItem;
            }
        }
        public void lcfp_SelectedIndexChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.ComboBoxEdit cmb = sender as DevExpress.XtraEditors.ComboBoxEdit;
            int index = 0;
            for (int i = 0; i < this.gridEditors.Count; i++)
            {

                if (this.gridEditors[i].Name == "楼层分配率")
                {
                    this.gridEditors.RemoveAt(i);
                }
                else if (this.gridEditors[i].Name == "楼层类型")
                {
                    index = i;
                }
            }
            string type = "";
            if (cmb == null)//第一次初始化
            {
                if (this.gridEditors[index].Value.ToString().Equals("电梯楼"))
                {
                    type = "DTL";
                }
                else if (this.gridEditors[index].Value.ToString().Equals("楼梯楼"))
                {
                    type = "LTL";
                }
            }
            else
            {
                if (cmb.SelectedItem.ToString().Equals("电梯楼"))
                {
                    type = "DTL";
                }
                else if (cmb.SelectedItem.ToString().Equals("楼梯楼"))
                {
                    type = "LTL";
                }
            }
            lcfp_tableName = m_DB_YSZB_Config.GetAttributeValueFromNodeNameWithSpecialAttribute("calContent", "value", m_calContent, "XZZB", "table", "name", "楼层分配率", "type", type);
            string fieldName = m_DB_YSZB_Config.GetAttributeValueFromNodeNameWithSpecialAttribute("calContent", "value", m_calContent, "XZZB", "field", "name", "楼层分配率", "type", type);
            string[] fieldArray = fieldName.Split('|');
            string field = fieldArray[0];
            for (int o = 1; o < fieldArray.Length; o++)
            {
                field += " ," + fieldArray[o];
            }
            string sqlStr = "select " + field + " from " + lcfp_tableName;
            DataTable dt = m_accessDB_xyzb.getDataTable(sqlStr);
            if (dt != null)
            {
                RepositoryItemComboBox dtl = new RepositoryItemComboBox();
                for (int i = 0; i < dt.Rows.Count; i++) 
                {
                   string cmbValue = dt.Rows[i][0].ToString() + " | " + dt.Rows[i][1].ToString();
                   dtl.Items.Add(cmbValue);
                }
                this.gridEditors.Insert(index + 1, new GridEditorItem(dtl, "楼层分配率", dtl.Items[0].ToString()));
            }

            this.gdvXZYZ.RefreshData();

        }
    }
    public class GridEditorItem
    {
        string fName;
        object fValue;
        RepositoryItem fRepositoryItem;

        public GridEditorItem(RepositoryItem fRepositoryItem, string fName, object fValue)
        {
            this.fRepositoryItem = fRepositoryItem;
            this.fName = fName;
            this.fValue = fValue;
        }
        public string Name { get { return this.fName; } }
        public object Value { get { return this.fValue; } set { this.fValue = value; } }
        public RepositoryItem RepositoryItem { get { return this.fRepositoryItem; } }
    }
    class GridEditorCollection : ArrayList
    {
        public GridEditorCollection()
        {
        }
        public new GridEditorItem this[int index] { get { return base[index] as GridEditorItem; } }
        public void Add(RepositoryItem fRepositoryItem, string fName, object fValue)
        {
            base.Add(new GridEditorItem(fRepositoryItem, fName, fValue));
        }
    }
}